/**
 * Copyright (C) 2011 PROCESSBASE Ltd.
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GPL as published by the Free Software Foundation version 3 of the License.
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License along with this
 * program; if not, see <http://www.gnu.org/licenses/>.
 */
package org.processbase.touchprocess.ui;

import com.vaadin.Application;
import com.vaadin.addon.touchkit.ui.TouchKitApplication;
import com.vaadin.service.ApplicationContext.TransactionListener;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.terminal.gwt.server.WebBrowser;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.http.HttpSession;
import org.processbase.ui.core.BPMModule;
import org.processbase.ui.core.Constants;

@SuppressWarnings("serial")
public class TouchProcessApplication extends TouchKitApplication implements TransactionListener {
    
    

    private static ThreadLocal<TouchProcessApplication> current = new ThreadLocal<TouchProcessApplication>();
    private HttpSession httpSession = null;
    private BPMModule bpmModule = null;
    private ResourceBundle messages = null;
    private String userName;
    
    private MobileMainWindow mobileMainWindow = null;
    static CustomizedSystemMessages customizedSystemMessages = new CustomizedSystemMessages();

    static {
        // reload on session expired
        customizedSystemMessages.setSessionExpiredCaption(null);
        customizedSystemMessages.setSessionExpiredMessage(null);
    }

    public static SystemMessages getSystemMessages() {
        return customizedSystemMessages;
    }
    LoginView loginView = null;

    @Override
    public void init() {
        setCurrent(this);
        if (!Constants.LOADED) {
            Constants.loadConstants();
        }
        initUI();
        if (getContext() != null) {
            getContext().addTransactionListener(this);
        }
    }

    public void initUI() {
        try {
            WebApplicationContext applicationContext = (WebApplicationContext) this.getContext();
            httpSession = applicationContext.getHttpSession();
            setLocale(applicationContext.getBrowser().getLocale());
            setMessages(ResourceBundle.getBundle("resources/MessagesBundle", getLocale()));
            mobileMainWindow = new MobileMainWindow(); 
            setMainWindow(mobileMainWindow);
            // Using mobile mail theme
            setTheme("touchprocess");
            getMainWindow().addApplicationIcon(getURL() + "VAADIN/themes/touchprocess/apple-touch-icon.png");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public boolean authenticate(String login, String password) throws Exception {
        BPMModule bpmm = new BPMModule(login);
        if (bpmm.checkUserCredentials(login, password)) {
            setUserName(login);
            String locale = bpmm.getUserMetadata("locale");
            if (locale != null) {
                setLocale(new Locale(locale));
                setMessages(ResourceBundle.getBundle("resources/MessagesBundle", getLocale()));
            }
            setBpmModule(bpmm);
            mobileMainWindow.setContent(new TabletMainView());
            return true;
        } else {
            throw new Exception(getPbMessages().getString("loginWindowException2"));
        }
    }

    @Override
    public void onBrowserDetailsReady() {
        WebBrowser browser = getBrowser();
        if (!browser.isTouchDevice()) {
            getMainWindow().showNotification(
                    "It seems that it's non touch device. You can use it for demo purposess.");
        }

        if (isSmallScreenDevice()) {
//            getMainWindow().setContent(new SmartphoneMainView());
            loginView = new LoginView();
            getMainWindow().setContent(loginView);
            loginView.initUI();
        } else {
            loginView = new LoginView();
            getMainWindow().setContent(loginView);
            loginView.initUI();
        }
    }

    public boolean isSmallScreenDevice() {
        float viewPortWidth = getMainWindow().getWidth();
        return viewPortWidth < 600;
    }

    public ResourceBundle getPbMessages() {
        return messages;
    }

    public void setMessages(ResourceBundle messages) {
        this.messages = messages;
    }

    /**
     * @return the current application instance
     */
    public static TouchProcessApplication getCurrent() {
        return current.get();
    }

    /**
     * Set the current application instance
     */
    public static void setCurrent(TouchProcessApplication application) {
        if (getCurrent() == null) {
            current.set(application);
        }
    }

    /**
     * Remove the current application instance
     */
    public static void removeCurrent() {
        current.remove();
    }

    /**
     * TransactionListener
     */
    public void transactionStart(Application application, Object transactionData) {
        if (application == this) {
            TouchProcessApplication.setCurrent(this);
            // Store current users locale
            setLocale(getLocale());
        }
    }

    public void transactionEnd(Application application, Object transactionData) {
        if (application == this) {
            // Remove locale from the executing thread
            removeCurrent();
        }
    }

    public BPMModule getBpmModule() {
        return bpmModule;
    }

    public void setBpmModule(BPMModule bpmModule) {
        this.bpmModule = bpmModule;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public void close() {
        super.close();
    }

    public MobileMainWindow getMobileMainWindow() {
        return mobileMainWindow;
    }
    
    
}
